package udp;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class EchoServer02 {
    private DatagramSocket socket;
    public EchoServer02(int port) throws Exception{
        socket=new DatagramSocket(port);
    }
    public void start() throws Exception  {
        System.out.println("服务器启动"  );
        while(true){  
            //接收客户请求
            DatagramPacket  request=new DatagramPacket(new byte[4096],4096);
            socket.receive(request);
            //转换为字符串
            String resPacket=new String(request.getData(),request.getOffset(),request.getLength());
            //根据请求计算返回的响应值
            String ret=process(resPacket);
            //用DatagramPacket封装响应内容
            DatagramPacket datagramPacket=new DatagramPacket(ret.getBytes(),
            ret.getBytes().length,request.getSocketAddress());
            //用send方法发送响应
            socket.send(datagramPacket);
            //打印日志
            System.out.printf("[%s,%d],req:%s,resp:%s",
            request.getAddress(),request.getPort(),resPacket,ret);
        }
    }
    public String process(String resPacket){
        return resPacket;                      
    }                              
    public static void main(String[] args) throws Exception {
        EchoServer02 echoServer02=new EchoServer02(9090);
        echoServer02.start(); 
    }
}
